package com.sfx.concurrent.demo.concurrent.visibility.interrupt;

import lombok.extern.slf4j.Slf4j;
@Slf4j(topic = "c.interruptTestDemo")
public class interruptTestDemo {

    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();
        Thread.sleep(3500);//3s后打断
        log.debug("停止监控");
        tpt.stop();
    }
}
//两阶段终止模式
@Slf4j(topic = "c.TwoPhaseTermination")
class TwoPhaseTermination{
    private Thread monitor;//监控线程
    //启动线程
    public void start(){
        //监控线程
         monitor = new Thread(()->{
           while(true){
               //获取打断标记
               Thread current = Thread.currentThread();//执行监控记录的线程
               if(current.isInterrupted()){//不会清除打断标记  interrupted静态方法会清楚打断标记
                   //如果被打断,料理完后事,就退出循环
                   log.debug("料理完后事,就退出循环!!!");
                   break;
               }
               //没有被打断,就睡眠1s之后,进行监控记录
               try {
                   Thread.sleep(1000);//可能被打断->触发异常进入catch块
                   log.debug("current : 执行监控记录");//可能被打断->打断标记为true下次不进入循环
               } catch (InterruptedException e) {
                   //sleep被打断后会触发异常,打断标记会被重置为false,所以需要重新设置打断标记
                   current.interrupt();
                  // e.printStackTrace();
               }
           }
        });
        //启动监控线程
        monitor.start();
    }
    //终止线程
    public void stop(){
        monitor.interrupt();//设置打断标记
    }
}
